package com.atguigu.gulimall.product.execption;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.app") //只捕获该包下的异常
public class GulimallExectionControllerAdvice {

    //处理服务器端校验异常
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public  R a(MethodArgumentNotValidException e){

        HashMap<String, Object> map = new HashMap<>();

        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            for (FieldError error : errors) {
                String name = error.getField();
                String message = error.getDefaultMessage();
                map.put(name,message);
            }
        }
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMessage()).put("data",map);
    }

//    //未知异常
//    @ExceptionHandler(Throwable.class)
//    public R handleException(Throwable e){
//        Logger logger = LoggerFactory.getLogger(GulimallExectionControllerAdvice.class);
//        logger.info("全局异常处理--未知异常："+e.getMessage());
//        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMessage());
//    }


}
